package com.deercrowing.takeaway.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deercrowing.takeaway.common.constant.MessageConstant;
import com.deercrowing.takeaway.common.exception.BusinessException;
import com.deercrowing.takeaway.common.properties.WeChatProperties;
import com.deercrowing.takeaway.common.util.CounterIDGenerator;
import com.deercrowing.takeaway.common.util.HttpClientUtil;
import com.deercrowing.takeaway.dao.UsersMapper;
import com.deercrowing.takeaway.entity.UsersEntity;
import com.deercrowing.takeaway.service.UsersService;
import org.codehaus.jettison.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户表(Users)表服务实现类
 *
 * @author guoyongxiang
 * @since 2024-07-25 10:39:19
 */
@Service
@Slf4j
public class UsersServiceImpl extends ServiceImpl<UsersMapper, UsersEntity> implements UsersService {

    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    UsersMapper usersMapper;

    @Autowired
    WeChatProperties weChatProperties;

    @Override
    public UsersEntity wxLogin(String code) throws JSONException {
        String openid = getOpenid(code);
        // 判断openid是否为空，如果为空表示登录失败，抛出业务异常
        if(openid == null){
            throw new BusinessException(MessageConstant.LOGIN_FAILED);
        }

        // 判断当前用户是否为新用户
        UsersEntity usersEntity = usersMapper.getByOpenid(openid);
        CounterIDGenerator counterIDGenerator = new CounterIDGenerator();

        // 如果是新用户，自动完成注册
        if(usersEntity == null){
            usersEntity = new UsersEntity();
            usersEntity
                       .setId(Long.parseLong(counterIDGenerator.generateID()))
                       .setOpenid(openid)
                       .setCreateTime(LocalDateTime.now())
                       .setName(openid)
                       .insert();
        }

        // 返回这个用户对象
        return usersEntity;
    }

    /**
     * 调用微信接口服务，获取微信用户的openid
     * @param code
     * @return
     */
    private String getOpenid(String code) throws JSONException {
        //调用微信接口服务，获得当前微信用户的openid
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        return openid;
    }
}

